<template>
  <div class="app-container">
    <div v-show="!detailedPageVisible">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="配置名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入配置名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="通知类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择通知类型" clearable>
            <el-option
              v-for="dict in dict.type.notify_config_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="服务商" prop="provider">
          <el-select v-model="queryParams.provider" placeholder="请选择服务商" clearable>
            <el-option
              v-for="dict in dict.type.notify_config_provider"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['notify:config:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['notify:config:remove']"
          >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['notify:config:export']"
          >导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['notify:config:import']"
          >导入
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="ID" align="center" prop="id" width="55"/>
        <el-table-column label="服务商" align="center" prop="provider">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.notify_config_provider" :value="scope.row.provider"/>
          </template>
        </el-table-column>
        <el-table-column label="配置名称" align="center" prop="name"/>
        <el-table-column label="通知类型" align="center" prop="type">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.notify_config_type" :value="scope.row.type"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['notify:config:edit']"
            >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDebugging(scope.row)"
              v-hasPermi="['notify:config:edit']"
            >调试
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="downloadConfig(scope.row)"
              v-hasPermi="['notify:config:edit']"
            >下载配置
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['notify:config:remove']"
            >删除
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleDetails(scope.row)"
            >通知记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>


    <!-- 添加或修改通知配置对话框 -->
    <notify-config-add-edit ref="NotifyConfigAddEdit"/>

    <!-- 通知记录页面 -->
    <detailed ref="Detailed"/>

    <!--    调试对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px">
      <el-form ref="debugForm" :model="debugForm" label-width="120px">

        <el-form-item label="通知配置" prop="config">
          <el-select v-model="debugForm.template" class="select-width">
            <el-option
              v-for="(item,i) in this.templateList"
              :key="item.id"
              :label="item.name"
              :value="item.template"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="变量" prop="variable">
          <el-input type="textarea" :rows="8" v-model="debugForm.variable"></el-input>
        </el-form-item>

        <el-footer>
          <div class="bottom-bar" style="text-align: right">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </el-footer>
      </el-form>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-form>
        <el-form-item prop="configLists">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入xls、xlsx格式文件。</span>
            </div>
          </el-upload>
        </el-form-item>
        <el-footer>
          <div class="bottom-bar" style="text-align: right">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </el-footer>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {listConfig, delConfig,sendNotify} from "@/api/notify/config";
import {listTemplate} from "@/api/notify/template";
import {getToken} from "@/utils/auth";
import Detailed from "./detailed";
import NotifyConfigAddEdit from "./notifyConfigAddEdit";
import {mapState} from "vuex";

export default {
  name: "Config",
  components: {
    Detailed,
    NotifyConfigAddEdit,
  },
  dicts: ['notify_config_type', 'notify_config_provider'],

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通知配置表格数据
      configList: [],
      configLists: "",
      // 通知模板数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/notify/config/import"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        provider: null,
        configuration: null,
        name: null,
        description: null,
        type: null,
      },
      // 调试查询参数
      queryDebug: {
        pageNum: 1,
        pageSize: 10,
        provider: null,
        template: null,
        name: null,
        type: null,
        id: null,
      },
      // 表单参数
      form: {},
      // 调试表单参数
      debugForm: {},
      // 表单校验
      rules: {
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
      }
    };
  },
  computed: {
    ...mapState({
      configData: state => state.config.configData,
      detailedPageVisible: state => state.config.detailedPageVisible,
    }),
  },
  watch: {
    configData() {
      this.getList();
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询通知配置列表 */
    getList() {
      this.reset();
      this.loading = true;
      listConfig(this.queryParams).then(response => {
        this.configList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 调试取消按钮
    cancelDebug() {
      this.open = false;
      this.resetDebug();
    },
    // 搜索条件重置
    resetQueryParams() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        provider: null,
        configuration: null,
        name: null,
        description: null,
        type: null,
        id: null,
      };
      this.resetForm("form");
    },
    // 调试搜索条件重置
    resetQueryDebug() {
      this.queryDebug = {
        pageNum: 1,
        pageSize: 10,
        provider: null,
        template: null,
        name: null,
        type: null,
        id: null,
      };
      this.resetForm("form");
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        provider: null,
        configuration: null,
        name: null,
        description: null,
        type: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    // 调试表单重置
    resetDebug() {
      this.debugForm = {
        id: null,
        template: null,
        provider: null,
        name: null,
        type: null,
        variable: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    //导入表单重置
    importReset() {
      this.upload = {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/notify/config/import"
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 调试按钮操作 */
    handleDebugging(row) {

      this.resetDebug();
      this.resetQueryDebug();
      this.open = true;
      this.title = "调试对话框";
      //查询对应的通知配置
      this.queryDebug.type = row.type;
      this.queryDebug.provider = row.provider;
      listTemplate(this.queryDebug).then(response => {

        this.templateList = response.rows;

      });
      this.queryDebug.id = row.id;


    },
    /** 查看调式记录 */
    handleDetails(row) {

      // 隐藏主页面显示详情页
      this.$store.commit("DETAILED_CONFIG_VISIBLE", true);
      // 传递数据给详情页面
      let configData = JSON.parse(JSON.stringify(row));
      this.$store.commit("CONFIG_DATA", configData);
      this.$refs.Detailed.getHistoryList(row.id);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.NotifyConfigAddEdit.handleAddConfig();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids;
      this.$refs.NotifyConfigAddEdit.handleUpdate(id);
    },
    /** 下载配置按钮 */
    downloadConfig(row) {
      this.queryParams.id = row.id
      this.download('notify/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)

      this.queryParams.id = null;

    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    /** 提交上传文件 */
    submitFileForm() {
      this.$refs.upload.submit();
      this.upload.open = false;
    },

    /** 调试提交按钮 */
    submitForm() {
      this.queryDebug.template = this.debugForm.template;

      sendNotify(this.queryDebug.id, {

        template:  this.queryDebug,
        context: JSON.parse(this.debugForm.variable || '{}'),

      }).then(res => {

        if (res.code === 200) {
          this.open = false;
          this.$modal.msgSuccess("发送成功");
        }
      }).catch(() => {
        this.open = false;
        this.$modal.msgSuccess("系统出错");

      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除ID为"' + ids + '"的数据项？').then(function () {
        return delConfig(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('notify/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮 */
    handleImport() {
      this.upload.title = "导入通知模板";
      this.upload.open = true;
    }
  }
};
</script>
